clc
clear

global R M SIG K s K_maxMCS TBS Pmax D TPC ALP KS P0;


R=2000;
M= 1:27;
SIG=[-3.4,-2.7,-1.7,-1,0,1,2,2.9,3.8,4,4.4,5.4,6.4,7.4,8.2,8.9,9.7,10.3,11.3,12.1,13,14,15,15.9,16.7,17.9,18.8];
K=1:50;
s1=zeros(1,50);
k_mcsTh=zeros(1,50);
for i=1:length(K)
    s1(i)=-3.4+(18.8+3.4)*rand;
    k_mcsTh(i)=length(SIG(SIG<=s1(i)));
end
KS=50;
P0=100;
TBS=TBsizeTable2get;
D=[100 712 872 1160 1416 1736 2088 2472 2792 3112 3496 4008 4584 5160 5736 6200 6456 7224 7992 8504 9144 9912 10680 11448 12216 12576 14688 ...
    568 744 936 1224 1480 1864 2216 2536 2984 3368 3752 4264 4776 5352 5992 6456 6712 7480 8248 9144 9912 10680 11448];
% D=[536 712 872 1160 1416 1480 1480 32 56 72 104 120 144 176 224 256 296 328 376 328 440 552 680 808 968 1096 1256 1384 ...
%    208 256 328 440 552 680 808 968 1096 1256 1384 208 256 328 440 552 680 808 968 1096 1256 1384];
Pmax=10000;
TPC=1;
ALP=0.8;

s=s1;
K_maxMCS=k_mcsTh;






c1=1.5;
c2=1.5;
maxgen=1000;
sizepop=100;

popmax=2;
popmin=-1;
Vmax=1.5;
Vmin=-1;

for i=1:sizepop
    pop(i,:)=initPop();
    V(i,:)=0.5*rands(1,50);
    pop(i,:)=fixMCS(pop(i,:));
    fitnessValue(i)=fitness(pop(i,:));
end

[bestfitness, bestIndex]=min(fitnessValue);
zbest=pop(bestIndex,:);
gbest=pop;
fitnessgbest=fitnessValue;
fitnesszbest=bestfitness;

for i=1:maxgen
    for j=1:sizepop
        V(j,:)=V(j,:)+c1*rand*(gbest(j,:)-pop(j,:))+c2*rand*(zbest-pop(j,:));
        V(j,find(V(j,:)>Vmax))=Vmax;
        V(j,find(V(j,:)<Vmin))=Vmin;
        
        pop(j,:)=pop(j,:)+0.3*V(j,:);
        pop(j,find(pop(j,:)>popmax))=popmax;
        pop(j,find(pop(j,:)<popmin))=popmin;
        
        pop(j,:)=fixMCS(pop(j,:));
        
        fitnessValue(j)=fitness(pop(j,:));
    end
    
    for j=1:sizepop
        if fitnessValue(j)>fitnessgbest(j);
            gbest(j,:)=pop(j,:);
            fitnessgbest(j)=fitnessValue(j);
        end
        
        if fitnessValue(j)>fitnesszbest
            zbest=pop(j,:);
            fitnesszbest=fitnessValue(j);
        end
    end
    result(i)=fitnesszbest;
end
